package com.hunlian.makelove.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hunlian.makelove.AppApplication;
import com.hunlian.makelove.R;
import com.hunlian.makelove.tools.MyToast;

import static com.hunlian.makelove.R.id.webView;

public class WebActivity extends BaseActivity {

    private WebActivity mActivity;
    private WebView mWebView;
    private String mTitle;
    private String mDescription;
    private String mUrlAddress;
    private String sWebContent;
    private static final int CALL_NET_EXCEPTION_ACTIVITY = 1;
    private RelativeLayout ll_title;
    private boolean mHideTitle;
    private String sPostData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_protocol);

        mActivity = this;
        mTitle = this.getIntent().getStringExtra("title");
        mUrlAddress = this.getIntent().getStringExtra("url");
        mHideTitle = this.getIntent().getBooleanExtra("hideTitle",false);
        sWebContent = this.getIntent().getStringExtra("content");
        sPostData = this.getIntent().getStringExtra("postData");

        mWebView = (WebView) this.findViewById(webView);


        ll_title = (RelativeLayout) this.findViewById(R.id.ll_title);
        TextView mTvTitle = (TextView) ll_title.findViewById(R.id.title);
        mTvTitle.setText(mTitle);
        Button btnR = (Button) ll_title.findViewById(R.id.btn_nav_right);
        btnR.setVisibility(View.GONE);
        ImageButton mBtnBack = (ImageButton) ll_title.findViewById(R.id.back);
        mBtnBack.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mActivity.finish();
            }

        });

        if(mHideTitle){
            ll_title.setVisibility(View.GONE);
        }

        final ProgressBar myProgressBar = (ProgressBar) this.findViewById(R.id.myProgressBar);
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    myProgressBar.setVisibility(View.INVISIBLE);
                } else {
                    if (View.INVISIBLE == myProgressBar.getVisibility()) {
                        myProgressBar.setVisibility(View.VISIBLE);
                    }
                    myProgressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

        });

        loadData();

    }

    protected void loadData() {
        WebSettings webSettings = mWebView.getSettings();
        // 设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        // 设置可以访问文件
        webSettings.setAllowFileAccess(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        // 设置支持缩放
        webSettings.setBuiltInZoomControls(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //加载过程中出现Uncaught TypeError: Cannot call method 'getItem' of null at这样的错误加上这句
        //参考自http://blog.csdn.net/yuri99/article/details/46378137
        webSettings.setDomStorageEnabled(true);


        // 加载需要显示的网页
        if(!TextUtils.isEmpty(mUrlAddress)&&TextUtils.isEmpty(sPostData)){
            mWebView.loadUrl(mUrlAddress);
        }else if(!TextUtils.isEmpty(mUrlAddress)&&!TextUtils.isEmpty(sPostData)){
            try {
                mWebView.postUrl(mUrlAddress, sPostData.getBytes()); //"userId=111&functionId=21".getBytes());

            }catch (Exception e){
                e.printStackTrace();
            }
        }else if(!TextUtils.isEmpty(sWebContent)){
            mWebView.loadData(sWebContent,"text/html; charset=UTF-8",null);//这种写法可以正确解码  
        }


        // 设置Web视图
        mWebView.setWebViewClient(new WebViewClientEx());
    }



    @Override
    // 设置回退
    // 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView.canGoBack()) {
                mWebView.goBack(); // goBack()表示返回WebView的上一页面
                return true;
            }else{
                mActivity.finish();
            }
            // 如果已经回到了无法回退的页面，则关闭此页
            return super.onKeyDown(keyCode, event);
        }
        return false;

    }

    // Web视图
    private class WebViewClientEx extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
/*			view.loadUrl(url);
			return true;*/
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
/*            NetExceptionActivity.startNetExceptionActivity(mActivity,
                    CALL_NET_EXCEPTION_ACTIVITY);
            MyToast.showShort(failingUrl);*/

            if (!AppApplication.networkAvailable) {
                MyToast.showShort("没有网络");
            }
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == CALL_NET_EXCEPTION_ACTIVITY){
            if(resultCode == RESULT_OK){
                mWebView.loadUrl(mUrlAddress);
            }
        }
    }
}
